<?
error_reporting(E_ERROR);

// find running web server software
define("HTTPD", $_SERVER['SERVER_SOFTWARE']);

// include needed files if necessary
$tmp = "config.inc.php";
include($tmp);

// If $cfg not set there is a problem with config.inc.php
if (!isset($cfg))
	return;

// fallback on apache mode if we are running apache
if (strstr(HTTPD, 'web-cp'))
	$cfg['httpd_mode'] = 'webcp';
else {
	$cfg['httpd_mode'] = 'apache';
	$tmp = "functions.inc.phps";
	include($tmp);
}

// Load Input Vars:
	$data = load_input_vars('data');
	$step = intval(load_input_vars('step'));

// Determine if the backend is down
if (!(is_readable($cfg['basedir'].$cfg['statustag'])) || ((is_readable($cfg['basedir'].$cfg['statustag'])) && (fileatime($cfg['basedir'].$cfg['statustag']) < (time() - 90)))) {
	chdir('../');
	$tmpbasedir = getcwd();
	if (!(is_readable($tmpbasedir.$cfg['statustag'])) || ((is_readable($tmpbasedir.$cfg['statustag'])) && (fileatime($tmpbasedir.$cfg['statustag']) < (time() - 90)))) {
		echo 'The web-cp backend must be running to complete setup.  Please start the backend and <a href="javascript: window.location.reload();">reload this page</a>.';
		return;
	}
}

// If unknown, determine which step to perform
if ($step == 0) {
	unset($data);
	if (!file_exists($cfg['basedir'].'/config.php')) {
 		$step = 1;
	} elseif ($cfg['serversselected'] != true) {
		$step = 2;
	} elseif ($cfg['initscriptslocated'] != true) {
		$step = 3;
	} elseif ($cfg['programslocated'] != true) {
		$step = 4;
	} elseif (!@mysql_connect($cfg['dbhost'], $cfg['dbuser'], $cfg['dbpass'], true)
	  || !@mysql_select_db($cfg['dbname'])
	  || !mysql_num_rows(mysql_query("SHOW TABLES FROM ".$cfg['dbname']))) {
		$step = 5;
	} else if (!$cfg['modulesselected']) {
		$step = 6;
	} else {
		send_header('Location: http://'.$_SERVER['HTTP_HOST'].':'.$cfg['port']."/setup.php");
	}
}
//set frontend vars
$cp = 'server';
$url = 'newaccount';
$current_url = 'setup_config.php';
// load default language
include("lang/".$cfg['defaultlang'].".phps");

// If data is set (i.e the submit button has been hit)
if (isset($data)) {
	if (is_array($data)) {

		switch(intval($step)) {
			// Step 1 - Config needs to be generated from information
			//  entered on form. Occurs if config.php doesn't exist
			case 1:
				//Set OS chosen into a var and deal with OS incompatibility
				$data['os'] = explode('/', $data['os']);
				$data['osversion'] = $data['os'][1];
				$data['os'] = $data['os'][0];
				if ($data['os'] == "windows") {
					echo "Windows is not supported at this time.";
					return;
				}
				// Enable NAT if necessary
				if ($data['sysipint'] != $data['sysipext']) {
					$data['NAT'] = true;
					$data['NAT-map1'] = $data['sysipint'].",".$data['sysipext'];
				}
			// Step 2 - Servers Need to be Selected
			case 2:
				// Decide what to do based on programs

			// Step 3 - Program location
			case 3:
			case 4:

				// Prepare config values
				$config = '';
				foreach ($data AS $key => $val) {
					if ($key != 'submit') {
						//add config var to $config string
						$config .= urlencode($key).'='.urlencode($val).'&';
						if ($key != 'key') {
							$cfg[$key] = $val;
						} else {
							$newkey = $val;
						}
					}
				}
				$config = substr($config, 0, -1);

				// Write config - runs for step 1, 2, 3
				if (!file_exists($cfg['basedir'].'/config.php')) {
					$action = 'setup';
				} else {
					$action = 'config';
				}

				if (!commit($action, $config)) {
					$error[] = 'Error: Could not write to "tag" directory. Please enable the '
					          .'web server to write to '.$cfg['basedir'].'/tag.';
				}

				if (isset($newkey)) {
					$cfg['key'] = $newkey;
				}

				break;

			// Database
			case 5:

				// Prepare config values
				$config = '';
				foreach ($data AS $key => $val) {
					if ($key != 'submit') {
						//add config var to $config string
						$config .= urlencode($key).'='.urlencode($val).'&';
						$cfg[$key] = $val;
					}
				}
				$config = substr($config, 0, -1);

				if (!commit('config', $config)) {
					$error[] = 'Error: Could not write to "tag" directory. Please enable the '
					          .'web server to write to '.$cfg['basedir'].'/tag.';
				} else {
					if (!@mysql_connect($data['dbhost'], $data['dbuser'], $data['dbpass'], true)) {
						$error[] = $T['err']['Could not connect to database server.'];
					} else {
						mysql_query('CREATE DATABASE '.$data['dbname']);
						if(!@mysql_select_db($data['dbname'])) {
							$error[] = mysql_error();
						} else {
							$sql_errors = import_sql_dump(file_get_contents($cfg['basedir'].'/webcp.sql'));
							if(empty($sql_errors)) {
								$sql_errors += import_sql_dump(file_get_contents($cfg['basedir'].'/help-'.$cfg['defaultlang'].'.sql'));
							}

							if(!empty($sql_errors)) {
								$error[] = $T['err']['Could not insert tables into database: '].$cfg['dbname'];
								$error[] = $T['Please complete this step manually and click submit.'];
								$error += $sql_errors;
							}
						}
					}
				}
				break;

			// Modules Need to be Selected
			case 6:
				$db = mysql_connect($cfg['dbhost'], $cfg['dbuser'], $cfg['dbpass'], true);
				if (!@mysql_select_db($cfg['dbname']))
					return;
				foreach ($data AS $key => $val) {
					if ($key != 'modulesselected') {
						$modname = str_replace('.mod.phps', '', $key);
						if($val=="true") {
							if (register_module($key)) {
								enable_module($key);
							} else {
								$error[] = $T['Modules']['Err']['Exclusion Exists'].' - '.$modname;
							}
						} else {
							if (disable_module($key)) {
								unregister_module($key);
							} else {
								$error[] = $T['Modules']['Err']['Dependency Exists'].' - '.$modname;
							}
						}
					}
				}
				if (empty($error)) {
					$config = 'modulesselected=true';
					if (!commit('config', $config) || !commit('reload-modules')) {
						$error[] = 'Error: Could not write to "tag" directory. Please enable the '
						          .'web server to write to '.$cfg['basedir'].'/tag.';
					} else {
						sleep(2);
						send_header('Location: http://'.$_SERVER['HTTP_HOST'].':'.$cfg['port'].'/setup.php');
						return;
					}
				}
				break;
			default:
				send_header('Location: http://'.$_SERVER['HTTP_HOST'].':'.$cfg['port'].'/setup.php');
				return;
				break;

		}
		if (!$error) {
			$step++;
		}
	}
}
// Start outputting the page - dependant on what has happened already
?>
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>web-cp setup script</title>
<meta name="description" content="web-cp setup script">
<style type="text/css">
<!--
/* Body Style */
body { font-family: Arial, Verdana, Sans-Serif; font-size: 14px; margin: 0; background-color: #F5F5F5; }
/* <a> Links Style */
a	{ text-decoration: underline;
		color: #2d2d2d;
	}
a:hover { text-decoration: underline;
		color: #464646;
	}
/* web-cp use the following classes */
/* Font Style & Types */
	.small	{ font-size: 12px; }
	.normal	{ font-size: 14px; }
	.big		{ font-size: 16px; }
/* Table Style */
	.tbltop { background-color: #5B7B9C; color: #f5f5f5; font-size: 14px; font-weight: bold; text-align: center; }
	.row1		{ background-color: #e9e9e9; font-size: 11px; text-align: right;}
	.row2		{ background-color: #E2EAF2; font-size: 11px; text-align: left;}
	.tblbg 	{ background-color: #DADADA; }
/* PopUp Help Style */
.popup {
	border: solid 1px #666666;
	padding: 1px;
	/*width: 200;*/
	background-color: #94B4D1;
	layer-background-color: #94B4D1;
	position: absolute;
	visibility: hidden;
}
-->
</style>
<!-- Scripting for page -->
<script language='JavaScript' src='script.js'></script>
</head>
<body><br>
<div id="HTTP Server" class="popup"><b>web-cp HTTP Server</b><br>Select the dedicated HTTP server used for the web-cp control panel.  The default is the bundled php server.</div>
<div id="Database Host" class="popup"><b>Database Host</b><br>The IP or Host Name of the computer that is running the MySQL database.</div>
<div id="Database User" class="popup"><b>Database User</b><br>The user that will be used to log into the Database Host</div>
<div id="Database Password" class="popup"><b>Database Password</b><br>The password that will be used to log into the Database Host. Can be left empty for no password.</div>
<div id="Database Name" class="popup"><b>Database Name</b><br>The name of the Database that web-cp tables will be imported into.</div>
<div id="Server Domain" class="popup"><b>Server Domain</b><br>The domain that will resolve to the server running web-cp. If DNS isn't set up yet it could also be in the form of an IP address.</div>
<div id="Server IP Int" class="popup"><b>Server IP Internal</b><br>The IP address that this web server uses internally on your network to talk to other local machines - used by the Apache Web server software.</div>
<div id="Server IP Ext" class="popup"><b>Server IP External</b><br>The IP address that this web server uses externally on your router or gateway to talk to all external machines on the web, this is the visible IP address of the server that the internet will see - used by DNS server software.</div>
<div id="Nameserver 1" class="popup"><b>Nameserver 1</b><br>The Primary Nameserver - needed for DNS system.</div>
<div id="Nameserver 2" class="popup"><b>Nameserver 2</b><br>The Secondary Nameserver - If you do not needthis then please set it to none.</div>
<div id="Admin E-Mail" class="popup"><b>Admin E-Mail</b><br>Email address that can be used to contact the system administrator.</div>
<div id="HDD Partition" class="popup"><b>HDD Partition</b><br>HDD Partition that domains will reside on, usually the partition /home is on, e.g. /dev/hda3</div>
<div id="Operating System" class="popup"><b>Operating System</b><br>The operating system that web-cp is running on.</div>
<div id="Default Language" class="popup"><b>Default Language</b><br>The language that will be set for all users until they change their language setting.</div>
<div id="Secret Key" class="popup"><b>Secret Key</b><br>A string of characters that should be kept secret. It will be used for encryption and verification.</div>
<div align="center"><big>web-cp setup script</big></div><br>
<table align="center">
<tr>
	<td <?=(($step == 1) ? 'class="tbltop"' : 'class="row1"');?>>&nbsp;<?=(($step > 1) ? '<a href="setup_config.php?step=1">' : '');?>Server Configuration</a>&nbsp;</td>
	<td> <img src="/icon/rightarrow.gif" width="24" height="24"> </td>
	<td <?=(($step == 2) ? 'class="tbltop"' : (($step > 2) ? 'class="row1"' : 'class="row2"'));?>>&nbsp;<?=(($step > 2) ? '<a href="setup_config.php?step=2">' : '');?>Select Servers</a>&nbsp;</td>
	<td> <img src="/icon/rightarrow.gif" width="24" height="24"> </td>
	<td <?=(($step == 3 || $step == 4) ? 'class="tbltop"' : (($step > 4) ? 'class="row1"' : 'class="row2"'));?>>&nbsp;<?=(($step > 3) ? '<a href="setup_config.php?step=3">' : '');?>Locate Programs</a>&nbsp;</td>
	<td> <img src="/icon/rightarrow.gif" width="24" height="24"> </td>
	<td <?=(($step == 5) ? 'class="tbltop"' : (($step > 5) ? 'class="row1"' : 'class="row2"'));?>>&nbsp;<?=(($step > 5) ? '<a href="setup_config.php?step=5">' : '');?>Database Configuration</a>&nbsp;</td>
	<td> <img src="/icon/rightarrow.gif" width="24" height="24"> </td>
	<td <?=(($step == 6) ? 'class="tbltop"' : 'class="row2"');?>>&nbsp;<?=(($step > 6) ? '<a href="setup_config.php?step=6">' : '');?>Select Modules</a>&nbsp;</td>
	<td> <img src="/icon/rightarrow.gif" width="24" height="24"> </td>
	<td class="row2">&nbsp;Primary Reseller&nbsp;</td>
	<td> <img src="/icon/rightarrow.gif" width="24" height="24"> </td>
	<td class="row2">&nbsp;Primary Domain&nbsp;</td>
	<td> <img src="/icon/rightarrow.gif" width="24" height="24"> </td>
	<td class="row2">&nbsp;Administrative Account&nbsp;</td>
</tr>
</table>
<?
// print error if applicable
if ($error) {
	echo "<center><br>&nbsp;&nbsp; ".implode("<br>\n&nbsp;&nbsp; ",$error)."<br>\n</center>";
}
// load and parse default skin
include("parser.inc.phps");

?>
<br>
<form action="<?=$current_url;?>" method="post" name="webcp" onSubmit="submitonce(this);">
<input type="hidden" name="step" value="<?php echo $step; ?>" />
<?php
// Produce different screen based on step
switch($step) {
	// No config file exists yet
	case 1:
		// Server base setup
		include("setup_step1.php");
		break;

	case 2:
		// Services and Programs setup
		include("setup_step2.php");
		break;

	case 3:
	case 4:
		// Database details setup
		include("setup_step3.php");
		break;

	case 5:
		// Service selection
		include("setup_step4.php");
		break;

	case 6:
		// Module selection
		include("setup_step5.php");
		break;
}
?>
<div align="right">
<input type="submit" name="data[submit]" value="Submit">
</div>
</div>
</td></tr></table>
</div>
</form>
</body>
</html>
